package http;

import checkcode.ImagePreProcess;
import configuration.RobConfiguration;
import enumeration.EnumRobChannel;
import http.util.ArrayUtil;
import http.util.HtmlUtil;
import http.util.ParseUtil;
import main.robClass;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import org.jsoup.Jsoup;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import robber.impl.CommonRobber;
import robber.impl.PERobber;
import timer.saveCookieManager;
import timer.saveRobberManager;
import user.IUser;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;


/**
 * 基础请求职责
 */
public class BasicRequest {
    public class BetterLoginUser {
        private String loginViewState;
        private HashSet<String> beforeLoginCookies = new HashSet<>();

        public String getRandomBeforeLoginCookies() {
//            System.out.println("查看数量"+getBeforeLoginCookies());
            return ArrayUtil.getRandomDataFromSet(getBeforeLoginCookies());
        }

        public HashSet<String> getBeforeLoginCookies() {
            return beforeLoginCookies;
        }

        public void setBeforeLoginCookies(HashSet<String> beforeLoginCookies) {
            this.beforeLoginCookies = beforeLoginCookies;
        }

        public String getLoginViewState() {
            return loginViewState;
        }

        public void setLoginViewState(String loginViewState) {
            this.loginViewState = loginViewState;
        }
    }

    private String ip = RobConfiguration.IP;
    private String url = RobConfiguration.URL;
    public static final String defaultHeader = "application/x-www-form-urlencoded;charset=gb2312";
    private Request basicRequest;
    private OkHttpClient defaultHttpClient;
    private OkHttpClient preInitClient;
    private OkHttpClient robInitClient;

    public static Map<Long, List<Cookie>> idAndCookies = new HashMap<Long, List<Cookie>>();
    private BetterLoginUser betterLoginUser;

    public BasicRequest() {
        this.betterLoginUser = new BetterLoginUser();
        this.defaultHttpClient = new BasicHttpClient().getDefaultClient();
        this.preInitClient = new BasicHttpClient().getPreInitClient();
        this.robInitClient = new BasicHttpClient().getRobInitClient();
        this.basicRequest = new Request.Builder()
                .addHeader("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
                .addHeader("connection", "keep-alive") //keep-alive
//                .addHeader("cookie", getCookie(url)) //"route=a79c11333bcfcab69beab260e38ff9cb; ASP.NET_SessionId=af4gtiqgxirq3p21hrrcsu55"
                .addHeader("host", getIp())
//                .addHeader("origin", getUrl())
//                .header("Accept-Encoding", "identity")
                .url(url)
                .build();
    }

    public String getIp() {
        return this.ip;
    }

    public String getUrl() {
        return this.url;
    }

    public OkHttpClient getPreInitClient() {
        return preInitClient;
    }

    public OkHttpClient getRobInitClient() {
        return robInitClient;
    }

    public OkHttpClient getDefaultHttpClient() {
        return defaultHttpClient;
    }

    public Request getBasicRequest() {
        //robClass.logger.info("basicRequest：" + basicRequest);
        return basicRequest;
    }

    public String getWithLoginCookie(String uri) {
        Request request = this.getBasicRequest().newBuilder()
                .url(url + uri)
                .get()
                .build();
        String res = null;
        try {
            Response response = getDefaultHttpClient().newCall(request).execute();
            res = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }

    public Response getWithLoginCookie2(String uri, String id) {
        //robClass.logger.info("getCookie:" + getCookie(Long.valueOf(id)));
        if (getCookie(Long.valueOf(id)) == null) return null;

        Request request = this.getBasicRequest().newBuilder()
                .header("cookie", getCookie(Long.valueOf(id)))
                .url(url + uri)
                .get()
                .build();
        try {
            Response response = getDefaultHttpClient().newCall(request).execute();
            //robClass.logger.info("response:" + response.toString());
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public String postWithLoginCookie(String uri, String bodyContent) {

        Request request = this.getBasicRequest().newBuilder()
//                .header("cookie", getCookie(url+uri)) //"route=a79c11333bcfcab69beab260e38ff9cb; ASP.NET_SessionId=af4gtiqgxirq3p21hrrcsu55"
                .url(url + uri) //xstyk.aspx?xh=1908010101&xm=%CB%D5%B3%AC%CF%CD&gnmkdm=N121205
                .post(RequestBody.create(MediaType.parse(defaultHeader), bodyContent))
                .build();

        String res = null;
        try {
            //    robClass.logger.info("postWithLoginCookieXX: ");
            //     robClass.logger.info(request.url());

            Response response = getDefaultHttpClient().newCall(request).execute();
            res = response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }


    public String postCommonWithLoginCookieAndViewState(String uri, String bodyContent, String xh, String commonCourseViewState, IUser user) {
//        System.out.println("postCommonWithLoginCookieAndViewState()");
        Request request = null;
        try {
            request = this.getBasicRequest().newBuilder()
                    .addHeader("Referer", url + "/xs_main.aspx?xh=" + xh)
                    .addHeader("cookie", user.getRandomCookie())
                    .url(url + uri)
                    .post(RequestBody.create(MediaType.parse(defaultHeader),
                            bodyContent + "&__VIEWSTATE=" +
                                    URLEncoder.encode(commonCourseViewState, "gb2312")))
                    .build();

//            System.out.println(bodyContent + "&__VIEWSTATE=" +
//                    URLEncoder.encode(commonCourseViewState, "gb2312"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String res = null;
        try {

            Response response = getDefaultHttpClient().newCall(request).execute();
            res = response.body().string();
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return res;
    }

    //synchronized
    public String postWithLoginCookieAndViewState(String uri, String bodyContent, String id, String className) {
//        robClass.logger.info("postWithLoginCookieAndViewState-id" + id);
//        robClass.logger.info("postWithLoginCookieAndViewState: " + url + uri);
//        robClass.logger.info("postWithLoginCookieAndViewState-getCookie(url+uri)" + getCookie(Long.valueOf(id)));
//        robClass.logger.info("postWithLoginCookieAndViewState-idToviewState" + OldUser.idToViewState);
//        robClass.logger.info("IdHAS? ViewState?" + OldUser.idToViewState.get(id+className));
        Request request = null;
//        try {
//            robClass.logger.info("发包内容" +bodyContent + "&__VIEWSTATE=" +
//                    URLEncoder.encode(OldUser.idToViewState.get(id+className), "gb2312"));
//NNNNE
//            request = this.getBasicRequest().newBuilder()
//                    .header("cookie", getCookie(Long.parseLong(id))) //"route=a79c11333bcfcab69beab260e38ff9cb; ASP.NET_SessionId=af4gtiqgxirq3p21hrrcsu55"
//                    .url(url + uri) //xstyk.aspx?xh=1908010101&xm=%CB%D5%B3%AC%CF%CD&gnmkdm=N121205
//                    .post(RequestBody.create(MediaType.parse(defaultHeader),
//                            bodyContent + "&__VIEWSTATE=" +
//                                    URLEncoder.encode(OldUser.idToViewState.get(id + className), "gb2312")))//VIEWSTATE
//                    .build();
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }

        String res = null;
        try {
//            robClass.logger.info("postWithLoginCookie3: 测试的request " + request.url());
            Response response = getDefaultHttpClient().newCall(request).execute();
            res = response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    public Response postWithLoginCookie2(String uri, String bodyContent, String cookieId) {
//        robClass.logger.info("postWithLoginCookie2: " + url + uri);
//        robClass.logger.info("postWithLoginCookie2-CC:" + cookieId);
        Request request = this.getBasicRequest().newBuilder()
                .url((url + uri)) //xstyk.aspx?xh=1908010101&xm=%CB%D5%B3%AC%CF%CD&gnmkdm=N121205
                .header("cookie", getCookie(Long.valueOf(cookieId))) //"route=a79c11333bcfcab69beab260e38ff9cb; ASP.NET_SessionId=af4gtiqgxirq3p21hrrcsu55"
                .post(RequestBody.create(MediaType.parse(defaultHeader), bodyContent))
                .build();
        try {
//            robClass.logger.info("cx:");
//            robClass.logger.info(request.toString());
//            robClass.logger.info(request.url());
            return getDefaultHttpClient().newCall(request).execute();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public String getCookie(long id) {
        //从数据库读 idAndCookies
        if (this.basicRequest != null) {
            StringBuilder cookieStr = new StringBuilder();
            List<Cookie> cookies = idAndCookies.get(id);
//            robClass.logger.info("getCookieId " + id + " || " + cookies);
            if (cookies == null || cookies.size() <= 0) {
                return null;
            }
            for (Cookie cookie : cookies) {
                cookieStr.append(cookie.name()).append("=").append(cookie.value() + ";");
            }
//            robClass.logger.info("cookieStr.toString()" + cookieStr.toString());
            return cookieStr.toString();
        }
        return null;
    }

//    public String getCookie(long id) {
//
//        if (this.basicRequest != null) {
//
//            StringBuilder cookieStr = new StringBuilder();
//            List<Cookie> cookies = idAndCookies.get(id);
//            robClass.logger.info("idAndCookies - - -:" + idAndCookies);
//            robClass.logger.info("cookie的id" + id);
////            robClass.logger.info("getCookieId " + id  +" || "+ cookies);
//            for (Cookie cookie : cookies) {
//                cookieStr.append(cookie.name()).append("=").append(cookie.value() + ";");
//            }
////            robClass.logger.info("cookieStr.toString()" + cookieStr.toString());
//            return cookieStr.toString();
//        }
//        return "";
//    }

    public void saveCookie(Long id, List<Cookie> cookies) {
        //robClass.logger.info("保存Cookie:" + cookies + " id:" + id);
        idAndCookies.put(id, cookies);
    }

    public String postWithBetterLoginCookie(String uri, String bodyContent, String cookieId) {
//        robClass.logger.info("postWithbetterLoginCookie2: " + url + uri);
//        robClass.logger.info("postWithbetterLoginCookie2-CC:" + cookieId);
//        robClass.logger.info("登录需要的cookie:" + getCookie(Long.valueOf(cookieId)));
        Request request = this.getBasicRequest().newBuilder()
                .url((url + uri)) //xstyk.aspx?xh=1908010101&xm=%CB%D5%B3%AC%CF%CD&gnmkdm=N121205
                .header("cookie", getCookie(Long.valueOf(cookieId))) //"route=a79c11333bcfcab69beab260e38ff9cb; ASP.NET_SessionId=af4gtiqgxirq3p21hrrcsu55"
                .post(RequestBody.create(MediaType.parse(defaultHeader), bodyContent))
                .build();
        try {
//            robClass.logger.info("cx:");
//            robClass.logger.info(request.toString());
//            robClass.logger.info(request.url());
            return getDefaultHttpClient().newCall(request).execute().body().string();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //todo okhttp 异步改造计划
    public Call postWithBetterLoginCookie(String uri, String bodyContent, String cookie, String id) {
        Request request = this.getBasicRequest().newBuilder()
                .url((url + uri))
                .header("cookie", cookie)
                .post(RequestBody.create(MediaType.parse(defaultHeader), bodyContent))
                .build();
//        robClass.logger.info("发包的：(url + uri)" + (url + uri));
        try {
            //Cookie storeCookie = Cookie.parse(HttpUrl.parse(RobConfiguration.URL), cookie);
            //saveCookie(Long.valueOf(id), List.of(storeCookie));
            //robClass.logger.info("保存登录需要的cookie:" + List.of(storeCookie));
//            robClass.logger.info("目前发包的cookie:" + cookie);
//            robClass.logger.info("目前发包的req:" + request.toString());
//            robClass.logger.info("目前发包的req:" + request.headers().toString());
            Call call = getDefaultHttpClient().newCall(request);
            return call;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 抢体育课
     */
//    public Call postWithbetterLoginCookieAndViewState(String uri, String bodyContent, String id, String className) {
//        Request request = null;
//        try {
//            request = this.getBasicRequest().newBuilder()
//                    .header("cookie", getCookie(Long.parseLong(id)))
//                    .url(url + uri)
//                    .post(RequestBody.create(MediaType.parse(defaultHeader),
//                            bodyContent + "&__VIEWSTATE=" +
//                                    URLEncoder.encode(PERobber.idToViewState.get(id + className), "gb2312")))//VIEWSTATE
//                    .build();
//            Call call = httpClient.newCall(request);
//            return call;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
//


    /**
     * 体育课 - 正常模式发包
     */
    public Call pe_postWithCookieAndViewState(String uri, String bodyContent, String cookie, String viewState) {
        Request request = null;
        try {
            request = this.getBasicRequest().newBuilder()
                    .header("cookie", cookie)
                    .url(url + uri)
                    .post(RequestBody.create(MediaType.parse(defaultHeader),
                            bodyContent + "&__VIEWSTATE=" + viewState))
                    .build();
            Call call = getDefaultHttpClient().newCall(request);
            return call;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 体育课 - 狂暴模式发包
     */
    public Call crazy_pe_postWithCookieAndViewState(String uri, String bodyContent, String cookie, String viewState) {
        Request request = null;
        try {
            request = this.getBasicRequest().newBuilder()
                    .header("cookie", cookie)
                    .url(url + uri)
                    .post(RequestBody.create(MediaType.parse(defaultHeader),
                            bodyContent + "&__VIEWSTATE=" + viewState))
                    .build();
            Call call = getRobInitClient().newCall(request);
            return call;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 与时俱进的ViewState
     */
    public void checkLoginPageAlive() {
        try {
//            betterLoginUser.setLoginViewState("dDwtMTM0OTIyMDA2Nzs7PpG0z9oK8vXhE7%2F53z2U1HXgaVl0");
//            System.out.println("checkLoginPageAlive");
            Request request = this.getBasicRequest().newBuilder()
                    .url((RobConfiguration.URL))
                    .addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Mobile Safari/537.36 Edg/92.0.902.84")
                    .addHeader("Referer", RobConfiguration.URL)
                    .get()
                    .build();
            Call call = getPreInitClient().newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    robClass.logger.info("checkLoginPageAlive - 网络异常");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String responseHtml = response.body().string();
                    response.close();
//                    robClass.logger.info("checkLoginPageAlive-2");
                    String newLoginViewState = HtmlUtil.getViewStateFromResponseHtml(responseHtml);
                    if (StringUtils.isBlank(newLoginViewState)) {
                        return;
                    }
                    String curLoginViewState = betterLoginUser.getLoginViewState();
                    if (curLoginViewState == null || curLoginViewState.equalsIgnoreCase(newLoginViewState)) {
//                        robClass.logger.info("this.betterLoginUser:" + newLoginViewState);
                        /**目前用不了下面这个*/
                        betterLoginUser.setLoginViewState(URLEncoder.encode(newLoginViewState, "gb2312"));
                    }
//                    betterLoginUser.setLoginViewState("dDwtMTM0OTIyMDA2Nzs7PpG0z9oK8vXhE7%2F53z2U1HXgaVl0");
                }
            });
//        HttpGet httpGet = new HttpGet(RobConfiguration.URL + "/default2.aspx");
//        RequestConfig requestConfig = RequestConfig.custom()
//                .setSocketTimeout(1500)
//                .setConnectTimeout(3000)
//                .setConnectionRequestTimeout(3000).build();
//        CloseableHttpAsyncClient client = HttpAsyncClients.custom()
//                .setDefaultRequestConfig(requestConfig)
//                .build();
//        client.start();

//            Future<HttpResponse> future = client.execute(httpGet, null);
//            HttpResponse indexResponse = future.get();
//            int status_code = indexResponse.getStatusLine().getStatusCode();
////            Lock viewStateLock = new ReentrantLock();
//            if (status_code == 200) {
//                robClass.logger.info("checkLoginPageAlive-2");
//                String newLoginViewState = HtmlUtil.getViewStateFromResponseHtml(EntityUtils.toString(indexResponse.getEntity()));
//                if (StringUtils.isBlank(newLoginViewState)) {
//                    return;
//                }
////                viewStateLock.lock();
//                String curLoginViewState = this.betterLoginUser.getLoginViewState();
//                if (curLoginViewState == null || curLoginViewState.equalsIgnoreCase(newLoginViewState)) {
//                    robClass.logger.info("this.betterLoginUser:" + newLoginViewState );
//                    this.betterLoginUser.setLoginViewState(URLEncoder.encode(newLoginViewState, "gb2312"));
////                    viewStateLock.unlock();
//                }
//            }
//            client.close();
        } catch (Exception e) {
            robClass.logger.info("checkLoginPageAlive - 网络异常");
            //e.printStackTrace();
        }
    }

    /**
     * 资源发包
     */
    public void getBeforeLoginCookie() {
//        System.out.println("getBeforeLoginCookie");
        try {
            Request request = null;
            if (RobConfiguration.ROB_CHANNEL.equals(EnumRobChannel.SPECIALITY)) {
                request = this.getBasicRequest().newBuilder()
                        .url((RobConfiguration.URL + RobConfiguration.DEFAULT_2))
                        .get()
                        .build();
            } else if (RobConfiguration.ROB_CHANNEL.equals(EnumRobChannel.UNDERGRADUATE)) {
                request = this.getBasicRequest().newBuilder()
                        .url((RobConfiguration.URL))
                        .get()
                        .build();
            }
            Call call = getPreInitClient().newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    robClass.logger.info("getBeforeLoginCookie - 网络异常");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    response.close();
                    String cookie = "";
                    List<String> cookies = response.headers("Set-Cookie");
                    /**判断可用cookie a c都不可返回抢课状态 b可以*/
                    //route=c2337810a5bcaf2ec197c551cceae905; route=a79c11333bcfcab69beab260e38ff9cb; route=2fb3815e28a93711a595e0fe7ad90e73;
                    for (String h_cookie : cookies) {
                        /**如果提前出现课表不返回抢课信息就需要这个  你需要手动去判断哪个route可以返回消息进行过滤*/
//                        if (!h_cookie.contains("2fb3815e28a93711a595e0fe7ad90e73") && !h_cookie.contains("ASP.NET_SessionId")) {
////                            System.out.println("h_cookie:" + h_cookie);
//                            /**失败重试会造成严重阻塞 以及大量发包 太危险*/
////                            getBeforeLoginCookie();
//                            return;
//                        }
//                        robClass.logger.info("h_cookie.getName():" + h_cookie);
                        cookie += h_cookie.split(";")[0] + ";";
                    }
//                    robClass.logger.info("添加的cookie:" + cookie);
                    betterLoginUser.getBeforeLoginCookies().add(cookie);
//                    System.out.println("超贤：" + betterLoginUser.getBeforeLoginCookies());
                }
            });
        } catch (Exception e) {
            robClass.logger.info("getBeforeLoginCookie - 执行异常");
        }

    }

    /**
     * betterUser 默认发包的节奏就可了
     */
    public void _login(IUser user) {
//        betterLoginUser.setLoginViewState("dDwtMTM0OTIyMDA2Nzs7PpG0z9oK8vXhE7%2F53z2U1HXgaVl0");
//        robClass.logger.info("尝试");
//        robClass.logger.info("尝试2:" + getBetterLoginUser().getLoginViewState());

        if (getBetterLoginUser().getLoginViewState() != null) {
            String randomBeforeLoginCookie = getBetterLoginUser().getRandomBeforeLoginCookies();

//            System.out.println(user.getCookies());
//            HashSet<String> cookies = user.getCookies();
//            List<String> list = new ArrayList(cookies);
//            list.sort(Comparator.naturalOrder());
//            String cookie = list.get(0);
//            randomBeforeLoginCookie=cookie;
//            System.out.println("_login 登录使用的Cookie:" + randomBeforeLoginCookie);

            if (StringUtils.isBlank(randomBeforeLoginCookie)) {
                robClass.logger.info(user.getUsername()+"缺少: randomBeforeLoginCookie");
                return;
            }
            String finalRandomBeforeLoginCookie = randomBeforeLoginCookie;
//            System.out.println("_login登录时候 用来下载验证码: randomBeforeLoginCookie:" + randomBeforeLoginCookie);
            if (RobConfiguration.ROB_CHANNEL.equals(EnumRobChannel.SPECIALITY)) {
                randomBeforeLoginCookie = randomBeforeLoginCookie.split(";")[0];
            }
            ImagePreProcess.downloadCode(randomBeforeLoginCookie);
            if (randomBeforeLoginCookie != null) {

                String fileName = finalRandomBeforeLoginCookie.split("=")[1].split(";")[0];
                File file = new File(RobConfiguration.IMG_ACCOUNT_CODE + "codebetterLogin_" + fileName + ".png");
                if (file.exists()) {
                    String resultCodeStr = null;
                    try {
                        resultCodeStr = ImagePreProcess.getAllOcr(RobConfiguration.IMG_ACCOUNT_CODE + "codebetterLogin_" + fileName + ".png");
                    } catch (Exception e) {
                        //e.printStackTrace();
                    }
                    if (!resultCodeStr.contains("#")) {
                        //验证码获取失败重试
                        String bodyContent = null;
                        //新变动
                        System.out.println("登录问题:" + user.getPassword());
                        bodyContent = "__VIEWSTATE=" + this.getBetterLoginUser().getLoginViewState() + "&__VIEWSTATEGENERATOR=92719903" + "&txtUserName=" + user.getUsername() + "&TextBox2=" + user.getPassword() + "&txtSecretCode=" + resultCodeStr + "&RadioButtonList1=%D1%A7%C9%FA&Button1=&lbLanguage=&hidPdrs=&hidsc=";
//                        System.out.println(bodyContent);
                        //携带验证码的cookie去发包
                        Request request = null;
                        if (RobConfiguration.ROB_CHANNEL.equals(EnumRobChannel.UNDERGRADUATE)) {
//                            System.out.println("EnumRobChannel.UNDERGRADUATE");
                            /**专科本科不一样的 请注意*/
                            request = this.getBasicRequest().newBuilder()
                                    .url(url + RobConfiguration.DEFAULT_2)

                                    .addHeader("Cookie", randomBeforeLoginCookie)
                                    .addHeader("Referer", RobConfiguration.URL + RobConfiguration.DEFAULT_2)
                                    .addHeader("cache-control", "max-age=0")
                                    .addHeader("content-type", "application/x-www-form-urlencoded")
                                    .addHeader("proxy-connection", "keep-alive")
                                    .addHeader("upgrade-insecure-requests", "1")
//                                    .addHeader("Origin", RobConfiguration.URL)
                                    .post(RequestBody.create(MediaType.parse(defaultHeader), bodyContent))
                                    .build();

                        } else if (RobConfiguration.ROB_CHANNEL.equals(EnumRobChannel.SPECIALITY)) {
                            request = this.getBasicRequest().newBuilder()
                                    .url(url + RobConfiguration.DEFAULT_2)
                                    .addHeader("Cookie", randomBeforeLoginCookie)
                                    .addHeader("Referer", RobConfiguration.URL + RobConfiguration.DEFAULT_2)
                                    .post(RequestBody.create(MediaType.parse(defaultHeader), bodyContent))
                                    .build();
                        }

                        //Call call = postWithBetterLoginCookie("/default2.aspx", bodyContent, randomBeforeLoginCookie, user.getUsername());
                        Call call = getPreInitClient().newCall(request);
//                        robClass.logger.info("识别的验证码为: " + resultCodeStr);
//                        String finalResultCodeStr = resultCodeStr;
                        call.enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                robClass.logger.info(user.getUsername() + "#BetterUser登录失败: 网络请求超时");
                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {

                                String responseHtml = response.body().string();
                                response.close();
                                if (ParseUtil.parseObjectMoved(responseHtml)) {
                                    String cookie = finalRandomBeforeLoginCookie;
//                                    robClass.logger.info(user.getUsername() + "#BetterUser登录成功" + "cookie:" + cookie);
                                    updateCookies(user, cookie);
                                }

                                /**此处LoginViewState设置为登录后获取的首个firstViewState*/
                                /**LoginViewState有两种 一种是登录前网页默认 一种是登陆后*/
//                                getBetterLoginUser().setLoginViewState(HtmlUtil.getViewStateFromResponseHtml(response.body().string()));
//                                response.close();

//                                String responseHtml = response.body().string();
//                                robClass.logger.info(responseHtml);
//                                Headers headers = response.headers();
//                                robClass.logger.info("headers:" + headers.toString());
//                                HttpUrl url = response.request().url();
//                                robClass.logger.info("R-headers:" + response.request().headers());
                                //List<Cookie> cookies = Cookie.parseAll(url, headers);
                                //robClass.logger.info("到手的cookies" + cookies);
//                                if (cookies != null) {
//                                    String cookie = okHttp3CookieToString(cookies);0

                                //getBetterLoginUser().getBeforeLoginCookies().remove(cookie);
//                                robClass.logger.info("到手的cookie" + cookie);

//                                }
//                                printLoginState(responseHtml);
//                                Response response1 = call.execute();
//                                HttpUrl url = response.request().url();
//                                Headers headers = response.headers();
//                                String responseHtml = response.body().string();
//                                List<Cookie> cookies = Cookie.parseAll(url, headers);
//                                if (cookies != null) {
//                                    String cookie = okHttp3CookieToString(cookies);
//                                    updateCookies(user, cookie);
//                                }
//                                getBetterLoginUser().getBeforeLoginCookies().remove(randomBeforeLoginCookie);
//                                printLoginState(responseHtml);
                            }
                        });
                    } else {
                        robClass.logger.info("验证码识别错误! [空文件/准确率错误]");
                        return;
                    }
                } else {
                    robClass.logger.info("找不到指定的png![空文件]");
                    return;
                }
            } else {
                robClass.logger.info("获取登录Cookie失败");
                return;
            }
        }
    }

    /**
     * OOUSER 默认发包的节奏就可了
     */
    public void login(IUser user, String uri, String bodyContent, Long id) {

//        robClass.logger.info("登录登录");
        Request request = getBasicRequest().newBuilder()
                .url(url + uri)
                .post(RequestBody.create(MediaType.parse(BasicRequest.defaultHeader), bodyContent))
                .build();
        Call call = getPreInitClient().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                robClass.logger.info("异步-登录失败: 网络请求超时");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                robClass.logger.info("登录登录 res:" + bodyContent.split("TextBox2")[1].split("&")[0]);
                //response = httpClient.newCall(request).execute();
//                String responseHtml = response.body().string();
                Headers headers = response.headers();
                HttpUrl url = request.url();
                List<Cookie> cookies = Cookie.parseAll(url, headers);
                if (cookies != null) {
//                    saveCookie(id, cookies);
//                    robClass.logger.info(cookies);
//                    robClass.logger.info("idAndCookies: " + idAndCookies);
//                    robClass.logger.info(user.toString());
                    String cookie = okHttp3CookieToString(cookies);
                    updateCookies(user, cookie);
                }
//                System.out.println(responseHtml.substring(0, 55));
//                printLoginState(responseHtml);
                response.close();
            }
        });
    }

    public String okHttp3CookieToString(List<Cookie> cookies) {
        StringBuilder cookieStr = new StringBuilder();
        if (cookies == null || cookies.size() <= 0) {
            return null;
        }
        for (Cookie cookie : cookies) {
            cookieStr.append(cookie.name()).append("=").append(cookie.value() + ";");
        }
        return cookieStr.toString();
    }


    /**
     * 获取资源 因此使用资源发包实例
     * 使用随机Cookie发包
     */
    public Response sync_getWithRandomCookie(String uri, IUser user) {
//        System.out.println("sync_getWithRandomCookie");
//        System.out.println(user.getRandomCookie());
//        System.out.println(url + uri);
        Request request = this.getBasicRequest().newBuilder()
                .addHeader("cookie", user.getRandomCookie())
                .url(url + uri)
                .get()
                .build();
        try {
            Response response = getPreInitClient().newCall(request).execute();
            robClass.logger.info("sync_getWithRandomCookie_response:" + response.toString());
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取资源 因此使用资源发包实例
     */
    public Call async_getWithRandomCookie(String uri, IUser user) {
        Request request = null;
        try {
            String randomCookie = user.getRandomCookie();
            if (StringUtils.isBlank(randomCookie)) {
                return null;
            }
            request = this.getBasicRequest().newBuilder()
                    .header("cookie", randomCookie)
                    .url(url + uri)
                    .get()
                    .build();
            Call call = getPreInitClient().newCall(request);
            return call;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    //接受id 19080101011 19080101012
//    public String post(String uri, String bodyContent, String id)  {
//        //robClass.logger.info("post中id " +id);
//        robClass.logger.info("url + uri: " + (url + uri));
//        Request request = this.getBasicRequest().newBuilder()
//                .url(url + uri) //xstyk.aspx?xh=1908010101&xm=%CB%D5%B3%AC%CF%CD&gnmkdm=N121205
//                .post(RequestBody.create(MediaType.parse(defaultHeader), bodyContent))
//                .build();
//        try {
//            return handlerResponseCookie(request, Long.valueOf(id));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    /**
     * 登录后更新Cookies 类似LRU算法
     */
    public void updateCookies(IUser user, String cookie) {
        ArrayList<String> userCookies = user.getCookies();
//        System.out.println("新来的: " + cookie);
        /**注意清理用户mysql的cookie*/
        if (!StringUtils.isBlank(cookie) && userCookies.size() > 10) {
//            System.out.println("触发cookie清理");
            final Iterator cur_itor_userCookies = userCookies.iterator();
            String del_out_Cookie = null;
            while (cur_itor_userCookies.hasNext()) {
                del_out_Cookie = (String) cur_itor_userCookies.next();
            }
            if (!StringUtils.isBlank(del_out_Cookie)) {
//                robClass.logger.info("删除的cookie:" + del_out_Cookie);
                user.getCookies().remove(del_out_Cookie);
            }
//            robClass.logger.info("淘汰旧的cookies后的目前cookie: " + userCookies);
        }
        userCookies.add(cookie);
        ArrayList<String> unique_userCookies = new ArrayList<>(new HashSet<>(userCookies));
        user.setCookies(unique_userCookies);
//        robClass.logger.info(new Date() + "#目前用户拥有的cookies:" + user.getCookies());
    }

    public void printLoginState(String responseHtml) {
        if (responseHtml != null) {
            String parseResult = ParseUtil.parseScript(responseHtml);
            if (parseResult == null) {
                robClass.logger.info(new Date() + "#正方系统 - 登录成功");
            } else {
                robClass.logger.info("正方系统 - 登录失败");
            }
        } else {
            robClass.logger.info("正方系统 - 登录失败");
        }
    }

    public BetterLoginUser getBetterLoginUser() {
        return betterLoginUser;
    }


    /**
     * 公选课发包相关
     */

    public String getCommonViewState(String uri, IUser user, String Cookie) throws IOException {
        Request request = this.getBasicRequest().newBuilder()
                .addHeader("Referer", url + "/xs_main.aspx?xh=" + user.getUsername())
                .addHeader("cookie", Cookie)
                .url(url + uri)
                .get()
                .build();
        Response response = getPreInitClient().newCall(request).execute();
        String responseHtml = response.body().string();
        return HtmlUtil.getViewStateFromResponseHtml(responseHtml);
    }


    synchronized
    public Response common_sync_getWithRandomCookie(IUser user, String cookie) {
        Request request = null;
        Call call = null;
        Response response = null;
        try {
            if (StringUtils.isBlank(cookie)) {
                return null;
            }
            String uri = "/xf_xsqxxxk.aspx?xh=" + user.getUsername() + "&xm=" + URLEncoder.encode(user.getStudentName(), "gb2312") + "&gnmkdm=N121203";
            request = this.getBasicRequest().newBuilder()
                    .addHeader("referer", url + "/xs_main.aspx?xh=" + user.getUsername())
//                    .addHeader("cookie", user.getRandomCookie())
                    .addHeader("cookie", cookie)
//                    .addHeader("cache-control", "no-cache")
//                    .addHeader("pragma", "no-cache")
//                    .addHeader("Upgrade-Insecure-Requests", "1")
                    .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36")
                    .url(url + uri)
                    .get()
                    .build();
            response = getPreInitClient().newCall(request).execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
//        String firstViewState = null;
//        try {
//            String randomCookie = user.getRandomCookie();
//            firstViewState = getCommonViewState(uri, user, randomCookie); /**先一个get包拿firstViewState*/
//            Request request_main = getBasicRequest().newBuilder()
//                    .addHeader("cookie", randomCookie)
//                    .addHeader("cache-control", "no-cache")
//                    .addHeader("pragma", "no-cache")
//                    .addHeader("Upgrade-Insecure-Requests", "1")
//                    .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36")
//                    .url(RobConfiguration.URL + "/xs_main.aspx?xh=" + user.getUsername())
//                    .get()
//                    .build();
//            Call call_main = getDefaultHttpClient().newCall(request_main);
//            call_main.enqueue(new Callback() {
//                @Override
//                public void onFailure(Call call, IOException e) {
//                }
//
//                @Override
//                public void onResponse(Call call, Response response) {
//                    response.close();
//                }
//            });
//
//
//            String bodyContent = "__EVENTTARGET=dpkcmcGrid%3AtxtPageSize&__EVENTARGUMENT=&ddl_kcxz=&ddl_ywyl=%D3%D0&ddl_kcgs=&ddl_xqbs=1&ddl_sksj=&TextBox1=&Button2=%C8%B7%B6%A8&dpkcmcGrid%3AtxtChoosePage=1&dpkcmcGrid%3AtxtPageSize=150";
////            System.out.println("common_sync_getWithRandomCookie");
////            System.out.println(url + uri);
////            System.out.println(user.getUsername());
//            Request request = null;
//            request = this.getBasicRequest().newBuilder()
//                    .addHeader("Referer", url + "/xs_main.aspx?xh=" + user.getUsername())
//                    .addHeader("cookie", randomCookie)
//                    .url(url + uri)
//                    .post(RequestBody.create(MediaType.parse(defaultHeader),
//                            bodyContent + "&__VIEWSTATE=" +
//                                    URLEncoder.encode(firstViewState, "gb2312")))
//                    .build();
//
////        System.out.println(request.toString());
//            Response response = getPreInitClient().newCall(request).execute();
//            robClass.logger.info("common_sync_getWithRandomCookie_response:" + response.toString());
//            return response;
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return null;

    }

    /**
     * async_search_common使用
     */
    public Call common_async_getXsqxxxkViewStateWithCookie(IUser user, String cookie) {
        Request request = null;
        Call call = null;
        try {
            if (StringUtils.isBlank(cookie)) {
                return null;
            }
            String uri = "/xf_xsqxxxk.aspx?xh=" + user.getUsername() + "&xm=" + URLEncoder.encode(user.getStudentName(), "gb2312") + "&gnmkdm=N121203";
            request = this.getBasicRequest().newBuilder()
                    .addHeader("referer", url + "/xs_main.aspx?xh=" + user.getUsername())
//                    .addHeader("cookie", user.getRandomCookie())
                    .addHeader("cookie", cookie)
//                    .addHeader("cache-control", "no-cache")
//                    .addHeader("pragma", "no-cache")
//                    .addHeader("Upgrade-Insecure-Requests", "1")
                    .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36")
                    .url(url + uri)
                    .get()
                    .build();
            call = getDefaultHttpClient().newCall(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return call;

    }

    public void common_async_getXsqxxxkPostViewStateWithCookie(CommonRobber commonRobber) {
        IUser user = commonRobber.getUser();
        HashMap<String, String> cookieAndFirstViewState = commonRobber.getRandomCookieAndFirstViewState();
//        System.out.println("common_async_getXsqxxxkPostViewStateWithCookie");
//        System.out.println(cookieAndFirstViewState);
        if (cookieAndFirstViewState == null || cookieAndFirstViewState.isEmpty()) {
            System.out.println(cookieAndFirstViewState);
            System.out.println("cookieAndFirstViewState_error_1");
            return;
        }
        if (cookieAndFirstViewState.keySet()==null||cookieAndFirstViewState.keySet().size() == 0) {
            System.out.println(cookieAndFirstViewState);
            System.out.println("cookieAndFirstViewState_error_2");
            return;
        }
        String randomCookie = cookieAndFirstViewState.keySet().stream().findFirst().get();
//        System.out.println("randomCookie:" + randomCookie);
        if (StringUtils.isBlank(randomCookie)) {
            System.out.println("randomCookie_error_2");
            return;
        }

        Request request = null;
        if (cookieAndFirstViewState.values()==null||(cookieAndFirstViewState.values().size() == 0)) {
            System.out.println("cookieAndFirstViewState.values()_error"+cookieAndFirstViewState.values());
            return;
        }

        String firstViewState = ArrayUtil.getRandomDataFromCollection(cookieAndFirstViewState.values());
        if (StringUtils.isBlank(firstViewState)) {
            System.out.println("firstViewState_error"+firstViewState);
            return;
        }

//        System.out.println("firstViewState:" + firstViewState);
        try {
            String bodyContent = "&__EVENTTARGET=dpkcmcGrid%3AtxtPageSize&__EVENTARGUMENT=&ddl_kcxz=&ddl_ywyl=%D3%D0&ddl_kcgs=&ddl_xqbs=1&ddl_sksj=&TextBox1=&Button2=%C8%B7%B6%A8&dpkcmcGrid%3AtxtChoosePage=1&dpkcmcGrid%3AtxtPageSize=150";
            String uri = "/xf_xsqxxxk.aspx?xh=" + user.getUsername() + "&xm=" + URLEncoder.encode(user.getStudentName(), "gb2312") + "&gnmkdm=N121203";
            try {
                String out = "__VIEWSTATE=" +
                        URLEncoder.encode(firstViewState, "gb2312") +
                        bodyContent;
                request = getBasicRequest().newBuilder()
                        .addHeader("referer", RobConfiguration.URL + "/xf_xsqxxxk.aspx?xh=" + user.getUsername() + "&xm=" + URLEncoder.encode(user.getStudentName(), "gb2312") + "&gnmkdm=N121203")
                        .addHeader("cookie", randomCookie)
//                        .addHeader("cache-control", "no-cache")
//                        .addHeader("pragma", "no-cache")
                        .url(RobConfiguration.URL + uri)
                        .post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=gb2312"), out))
                        .build();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            Call call = getPreInitClient().newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res = response.body().string();
                    response.close();
                    //System.out.println("获取到postViewState" + res);
                    String postViewState = HtmlUtil.getViewStateFromResponseHtml(res);

                    /**过滤没用的viewstate*/
                    if (!StringUtil.isBlank(postViewState) && postViewState.length() > 10000) {
                        //System.out.println("postViewState:" + postViewState);
                        commonRobber.addCookieAndPostViewState(randomCookie, postViewState);
                        //System.out.println("CookieAndPostViewState:" + commonRobber.getCookieAndPostViewState());
                        /**序列化进数据库
                         * 保证程序崩溃重启立刻进行抢课
                         * 不需再做前置操作*/
                        saveCookieManager.updateUserToGlobalIdAndCookies(commonRobber.getUser());
                        saveRobberManager.updateUserToGlobalIdAndRobberInfo(commonRobber);

                    }
                }
            });
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return;
    }

    public Request common_rob_request(String uri, String bodyContent, String cookie, String postViewState) {
        try {
            String out = "__EVENTTARGET=&__EVENTARGUMENT=" + "&__VIEWSTATE=" +
                    URLEncoder.encode(postViewState, "gb2312") +
                    bodyContent;
            return this.getBasicRequest().newBuilder()
                    .addHeader("referer", url + uri)
                    .addHeader("cookie", cookie)
//                    .addHeader("cache-control", "no-cache")
//                    .addHeader("pragma", "no-cache")
                    .url(url + uri)
                    .post(RequestBody.create(MediaType.parse(defaultHeader), out))
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 公选课 - 正常模式发包
     */
    public Call common_postWithCookieAndViewState(String uri, String bodyContent, String cookie, String postViewState) {
        try {
            Call call = getDefaultHttpClient().newCall(common_rob_request(uri, bodyContent, cookie, postViewState));
            return call;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 公选课 - 狂暴模式发包
     */
    public Call crazy_common_postWithCookieAndViewState(String uri, String bodyContent, String cookie, String postViewState) {
        try {
            Call call = getRobInitClient().newCall(common_rob_request(uri, bodyContent, cookie, postViewState));
            return call;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String postCommonWithLoginCookieAndViewState2(String uri, String bodyContent, String xh, String commonCourseViewState, IUser user, String cookie) {

        Request request = null;
        try {
            String out = "__EVENTTARGET=&__EVENTARGUMENT=" + "&__VIEWSTATE=" +
                    URLEncoder.encode(commonCourseViewState, "gb2312") +
                    bodyContent;
            request = this.getBasicRequest().newBuilder()
                    .addHeader("referer", url + uri)
//                    .addHeader("cookie", user.getRandomCookie())
                    .addHeader("cookie", cookie)
                    .addHeader("cache-control", "no-cache")
                    .addHeader("pragma", "no-cache")
                    .url(url + uri)
                    .post(RequestBody.create(MediaType.parse(defaultHeader), out))
                    .build();
//            System.out.println(out);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String res = null;
        try {

            Response response = getDefaultHttpClient().newCall(request).execute();
            res = response.body().string();
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return res;
    }
//    public Call common_async_getXsqxxxkViewStateWithRandomCookie(IUser user) {
//        Request request = null;
//        try {
//            String uri ="/xf_xsqxxxk.aspx?xh=" + user.getUsername() + "&xm=" + URLEncoder.encode(user.getStudentName(), "gb2312") + "&gnmkdm=N121203";
//            String randomCookie = user.getRandomCookie();
//            if (StringUtils.isBlank(randomCookie)) {
//                return null;
//            }
//            request = this.getBasicRequest().newBuilder()
//                    .addHeader("Referer", url + "/xs_main.aspx?xh=" + user.getUsername())
//                    .addHeader("cookie", user.getRandomCookie())
//                    .addHeader("cache-control", "no-cache")
//                    .addHeader("pragma", "no-cache")
//                    .addHeader("Upgrade-Insecure-Requests", "1")
//                    .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36")
//                    .url(url + uri)
//                    .get()
//                    .build();
//            Call call = getPreInitClient().newCall(request);
//            return call;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

}

